﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entities;
using Logic;
using VotanetWebSite.Classes;
using System.Linq;
using System.Data;
using WebLog;


namespace VotanetWebSite.Acceso_Administrador
{
    public partial class Administracion_Votacion : System.Web.UI.Page
    {
        protected readonly string KEY = ConfigurationManager.AppSettings["KEY"].ToString();
        protected readonly string USER_MAIL = ConfigurationManager.AppSettings["USER"].ToString();
        protected readonly string USER_PASSWORD = ConfigurationManager.AppSettings["PASSWORD"].ToString();
        protected readonly string MAIL_SERVER = ConfigurationManager.AppSettings["MAIL_SERVER_NAME"].ToString();

        protected Users GetUser()
        {
            return Session["administrador"] as Users;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (GetUser() != null)
                {

                    LoadChexBoxRoles();
                    LoadUser(GetUser());
                    LoadVotingGrid();
                    LoadGridUser();
                    LoadLogGrid();
                }
                else
                {
                    Response.RedirectPermanent("~/Login_Usuario.aspx");
                }
            }
        }

        private void LoadLogGrid()
        {
            grillaLog.DataSource = GetListLog();
            grillaLog.DataBind();
        }

        private List<WebLogEntity> GetListLog()
        {
            return new WebLogLogic().GetListLogsLogic();
        }

        private void LoadUser(Users user)
        {
            lblNombreUsuarioLogin.Text = user.GetFullName();
        }

        #region Metodos Candidatos
        protected void LoadVotingGrid()
        {
            GridVotaciones.DataSource = GetListVoting();
            GridVotaciones.DataBind();
        }

        protected List<Entities.Group> GetListOfGroup()
        {
            return new VoterLogic().GetListGroupLogic(KEY);
        }

        protected List<string> GetListCandidateOffice()
        {
            return new VotingLogic().GetListCandidatesOfficesLogic();
        }

        protected List<Voting> GetListVoting()
        {
            return new VotingLogic().GetListVotingLogic(KEY);

        }

        protected void GridVotaciones_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                VotingLogic votingLogic = new VotingLogic();
                Voting voting = e.Row.DataItem as Voting;
                GridView gv = e.Row.FindControl("GridCandidatos") as GridView;
                if (voting != null && gv != null)
                {
                    List<Candidate> listCandidates = votingLogic.GetListCandidatesLogic(KEY, voting.id);
                    if (listCandidates != null)
                    {
                        gv.DataSource = listCandidates;
                        gv.DataBind();
                    }
                }
            }
        }


        //protected List<Candidate> ObtenerCandidatos(string llaveEncriptar, string votingId)
        //{
        //    return new VotingLogic().GetListCandidatesLogic(llaveEncriptar, votingId);
        //    //return null;
        //}

        //protected void BtnEditarCandidato_Click(object sender, EventArgs e)
        //{
        //    EditCandidate();
        //}

        //protected void EditCandidate()
        //{
        //    Candidate candidate = new VotingLogic().GetCandidateByIdLogic(HiDEditar.Value, KEY, false);
        //    string oldTableName = candidate.nameSQLTable;
        //    string oldProcedureName = candidate.nameSQLProcedure;
        //    string oldPictureName = candidate.pictureString;
        //    candidate.name = txtnombre.Text;
        //    candidate.middleName = txtSegundoNombre.Text;
        //    candidate.lastName = txtApellido.Text;
        //    candidate.secondLastName = txtSegundoApellido.Text;
        //    candidate.email = txtEmail.Text;
        //    candidate.office = ddlCargo.SelectedValue;
        //    candidate.telephone = txtTelefono.Text;
        //    candidate.cellPhone = txtCelular.Text;
        //    candidate.pictureString = GetPictureName(oldPictureName, candidate.name, candidate.lastName);

        //    bool response = new VotingLogic().UpdateCandidateLogic(candidate, oldTableName, oldProcedureName);

        //    if (response)
        //    {
        //        CleanFormCandidate();
        //        RenamePicture(oldPictureName, candidate.pictureString);
        //        LoadGroupGrid();
        //        Messages.Show(Page, Messages.DATA_UPDATED);
        //    }
        //    else
        //    {
        //        CleanFormCandidate();
        //        Messages.Show(Page, Messages.NO_DATA_UPDATED);
        //    }

        //}

        protected void RenamePicture(string oldName, string newName)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath("~/Images/CandidatePicture/" + oldName)))
            {
                File.Move(HttpContext.Current.Server.MapPath("~/Images/CandidatePicture/" + oldName), HttpContext.Current.Server.MapPath("~/Images/CandidatePicture/" + newName));
            }
            else
            {
                Messages.Show(Page, Messages.INVALID_ENTRY, "Editar_Candidatos.aspx");
            }
        }

        protected string GetPictureName(string oldName, string name, string lastName)
        {
            string[] extension = oldName.Split('.');
            return "Imagen" + name + lastName + "." + extension[1];
        }

        //protected void CleanFormCandidate()
        //{
        //    txtnombre.Text = string.Empty;
        //    txtSegundoNombre.Text = string.Empty;
        //    txtApellido.Text = string.Empty;
        //    txtSegundoApellido.Text = string.Empty;
        //    txtEmail.Text = string.Empty;
        //    txtTelefono.Text = string.Empty;
        //    txtCelular.Text = string.Empty;
        //    HiDEditar.Value = "0";
        //    Hideliminar.Value = "0";
        //}

        //protected void BtnEliminar_Click(object sender, EventArgs e)
        //{
        //    DeleteCandidate();
        //}

        //private void DeleteCandidate()
        //{
        //    VotingLogic voterLogic = new VotingLogic();
        //    Candidate candidate = voterLogic.GetCandidateByIdLogic(Hideliminar.Value, KEY, false);
        //    bool response = voterLogic.DeleteCandidateLogic(candidate);

        //    if (response)
        //    {
        //        CleanFormCandidate();
        //        DeletePicture(candidate.pictureString);
        //        LoadGroupGrid();
        //        Messages.Show(Page, Messages.DATA_ELIMINATED);
        //    }
        //    else
        //    {
        //        CleanFormCandidate();
        //        Messages.Show(Page, Messages.NO_DATA_ELIMINATED);
        //    }
        //}

        private void DeletePicture(string name_Fotografia)
        {
            if (File.Exists(HttpContext.Current.Server.MapPath("~/Images/CandidatePicture/" + name_Fotografia)))
            {
                File.Delete(HttpContext.Current.Server.MapPath("~/Images/CandidatePicture/" + name_Fotografia));
            }
            else
            {
                Messages.Show(Page, Messages.INVALID_ENTRY, "Editar_Candidatos.aspx");
            }
        }
        #endregion

        #region Metodos Usuario

        protected int ValidateRoles()
        {
            int cont = 0;
            foreach (ListItem item in checkRolesUsuarios.Items)
            {
                if (item.Selected == true)
                {
                    cont++;
                    break;
                }
            }
            return cont;
        }

        protected void LoadChexBoxRoles()
        {
            checkRolesUsuarios.DataSource = GetRoles();
            checkRolesUsuarios.DataTextField = "description";
            checkRolesUsuarios.DataValueField = "id";
            checkRolesUsuarios.CssClass = "label12";
            checkRolesUsuarios.DataBind();
        }

        protected List<Rol> GetRoles()
        {
            return new UserLogic().GetListRolesLogic(KEY);
        }

        protected void LoadGridUser()
        {
            GridListaUsuario.DataSource = GetListUser();
            GridListaUsuario.DataBind();
        }

        protected void BotonGuardarUsuario_Click(object sender, EventArgs e)
        {
            SaveUser();
        }

        protected void SaveUser()
        {
            if (ValidateRoles() > 0)
            {
                Users user = new Users();
                UserLogic userLogic = new UserLogic();
                user.id = userLogic.DecryptDataLogic(HiddenFieldUsuario.Value, KEY);
                user.rut = txtRutUsuario.Text;
                user.name = txtNombreUsuario.Text;
                user.lastName = txtApellidoUsuario.Text;
                user.email = txtEmailUsuario.Text;
                if (chboxBloqueadoUsuario.Enabled == true)
                {
                    if (chboxBloqueadoUsuario.Checked)
                    {
                        user.blocked = true;
                    }
                    else
                    {
                        user.blocked = false;
                    }
                }
                else
                {
                    user.blocked = false;
                }

                user.registrationDate = DateTime.Now;
                user.secondLastName = txtSegundoApellidoUsuario.Text;
                user.middleName = txtSegundoNombreUsuario.Text;
                user.telephone = txtTelefonoUsuario.Text;
                user.cellPhone = txtCelularUsuario.Text;
                foreach (ListItem item in checkRolesUsuarios.Items)
                {
                    if (item.Selected == true)
                    {
                        user.usersRoles.Add(new Rol() { id = item.Value, description = item.Text });
                    }
                }



                if (user.id == null)
                {
                    List<Users> userList = userLogic.SearchUsersByRutLogic(user, KEY);
                    if (userList == null)
                    {
                        Messages.Show(Page, Messages.RUT_EXIST);
                        BotonGuardarUsuario.Enabled = true;
                    }
                    else
                    {
                        if (userList.Count > 0)
                        {
                            Messages.Show(Page, Messages.RUT_EXIST);
                            BotonGuardarUsuario.Enabled = true;
                        }
                        else
                        {
                            InsertarUsuario(user, userLogic);
                        }
                    }
                }

                else
                {
                    UpdateUser(user, userLogic);
                }
            }
            else
            {
                Messages.Show(Page, Messages.INVALID_ROL);
            }
        }

        protected void InsertarUsuario(Users user, UserLogic userLogic)
        {
            bool response = userLogic.InsertUserLogic(user, KEY, USER_MAIL, USER_PASSWORD, MAIL_SERVER);
            if (response)
            {
                CleanFormUser();
                LoadGridUser();
                Messages.Show(Page, Messages.DATA_SAVED);
            }
            else
            {
                CleanFormUser();
                LoadGridUser();
                Messages.Show(Page, Messages.NO_DATA_SAVED);
            }
        }

        protected void UpdateUser(Users user, UserLogic userLogic)
        {
            bool response = userLogic.UpdateUserByIdLogic(user, KEY);
            if (response)
            {
                CleanFormUser();
                LoadGridUser();
                ChangeBlockedState(false);
                Messages.Show(Page, Messages.DATA_UPDATED);
            }
            else
            {
                CleanFormUser();
                Messages.Show(Page, Messages.NO_DATA_UPDATED);
            }
        }

        protected void CleanFormUser()
        {
            txtRutUsuario.Text = string.Empty;
            txtNombreUsuario.Text = string.Empty;
            txtApellidoUsuario.Text = string.Empty;
            txtEmailUsuario.Text = string.Empty;
            txtSegundoApellidoUsuario.Text = string.Empty;
            txtSegundoNombreUsuario.Text = string.Empty;
            txtTelefonoUsuario.Text = string.Empty;
            txtCelularUsuario.Text = string.Empty;
            HiddenFieldUsuario.Value = "0";
            hidIdUsuario.Value = "0";
            hidEmailUsuario.Value = "0";
            txtEditorEmailUsuario.Text = string.Empty;
            chboxBloqueadoUsuario.Checked = false;
            chboxBloqueadoUsuario.Visible = false;
            checkRolesUsuarios.ClearSelection();
        }

        protected void BotonBuscarUsuario_Click(object sender, EventArgs e)
        {
            ImageButton button = (ImageButton)sender;
            switch (button.CommandName.ToLower())
            {
                case "rut":
                    string rut = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaUsuario$ctl01$textboxRutUsuario"];
                    Users user = new Users();
                    user.rut = rut;
                    ShowSearchResults(new UserLogic().SearchUsersByRutLogic(user, KEY));
                    CleanFormUser();
                    break;

                case "name":
                    string name = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaUsuario$ctl01$textboxNombreUsuario"];
                    ShowSearchResults(new UserLogic().SearchUsersByNameLogic(name, KEY));
                    CleanFormUser();
                    break;

                case "lastName":
                    string lastName = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaUsuario$ctl01$textboxApellidoUsuario"];
                    ShowSearchResults(new UserLogic().SearchUsersByLastNameLogic(lastName, KEY));
                    CleanFormUser();
                    break;

                case "email":
                    string email = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaUsuario$ctl01$textboxEmailUsuario"];
                    ShowSearchResults(new UserLogic().SearchUsersByEmailLogic(email, KEY));
                    CleanFormUser();
                    break;

                case "telephone":
                    string telephone = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaUsuario$ctl01$textboxTelefonoUsuario"];
                    ShowSearchResults(new UserLogic().SearchUsersByTelephoneLogic(telephone, KEY));
                    CleanFormUser();

                    break;
                case "cellphone":
                    string cellphone = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaUsuario$ctl01$textboxCelularUsuario"];
                    ShowSearchResults(new UserLogic().SearchUsersByCellPhoneLogic(cellphone, KEY));
                    CleanFormUser();
                    break;

                case "dateview":
                    string date = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaUsuario$ctl01$textboxFechaUsuario"];
                    if (!string.IsNullOrWhiteSpace(date))
                    {
                        ShowSearchResults(new UserLogic().SearchUsersByDateLogic(Convert.ToDateTime(date), KEY));
                        CleanFormUser();
                    }
                    else
                    {
                        ShowSearchResults(new UserLogic().SearchUsersByDateLogic(new DateTime(), KEY));
                        CleanFormUser();
                    }
                    break;

                case "blockedview":
                    string blocked = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaUsuario$ctl01$ddlBloqueadoUsuario"];
                    ShowSearchResults(new UserLogic().SearchUsersByBlockedLogic(blocked, KEY));
                    CleanFormUser();
                    break;

                case "rolesview":
                    string rolesview = Request.Params["ctl00$ContentPlaceHolderMaestro$GridListaUsuario$ctl01$ddlRolUsuarios"];
                    ShowSearchResults(new UserLogic().SearchUsersByRolLogic(rolesview, KEY));
                    CleanFormUser();
                    break;
                default:
                    CleanFormUser();
                    LoadGridUser();
                    break;
            }
        }

        protected void ShowSearchResults(List<Users> lista)
        {
            if (lista != null && lista.Count > 0)
            {
                GridListaUsuario.DataSource = lista;
                GridListaUsuario.DataBind();
            }
            else
            {
                LoadGridUser();
                Messages.Show(Page, Messages.USER_NOT_EXIST);
            }
        }

        protected List<Users> GetListUser()
        {
            return new UserLogic().GetListUsersLogic(KEY);
        }

        protected void GridListaUsuario_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "editar":
                    LoadUser(e.CommandArgument.ToString());
                    ChangeBlockedState(true);
                    break;

                case "password":
                    Users user = new UserLogic().GetUserByIdLogic(e.CommandArgument.ToString(), KEY);
                    if (user != null)
                    {
                        UserLogic userLogic = new UserLogic();
                        if (userLogic.ChangePasswordLogic(user, USER_MAIL, USER_PASSWORD, MAIL_SERVER))
                        {
                            Messages.Show(Page, Messages.PASSWORD_CHANGED);
                        }
                        else
                        {
                            Messages.Show(Page, Messages.NO_PASSWORD_CHANGED);
                        }
                    }
                    else
                    {
                        Messages.Show(Page, Messages.NO_PASSWORD_CHANGED);
                    }

                    break;
            }
        }

        protected void LoadUser(string id)
        {
            CleanFormUser();
            UserLogic userLogic = new UserLogic();
            Users user = userLogic.GetUserByIdLogic(id, KEY);

            if (user != null)
            {
                txtRutUsuario.Text = user.rut;
                txtNombreUsuario.Text = user.name;
                txtApellidoUsuario.Text = user.lastName;
                txtEmailUsuario.Text = user.email;
                txtSegundoApellidoUsuario.Text = user.secondLastName;
                txtSegundoNombreUsuario.Text = user.middleName;
                txtTelefonoUsuario.Text = user.telephone;
                txtCelularUsuario.Text = user.cellPhone;
                chboxBloqueadoUsuario.Checked = user.blocked;
                HiddenFieldUsuario.Value = userLogic.EncriptDataLogic(user.id.ToString(), KEY);

                foreach (ListItem item in checkRolesUsuarios.Items)
                {
                    foreach (Rol r in user.usersRoles)
                    {
                        if (item.Value == r.id.ToString())
                        {
                            item.Selected = true;
                        }
                    }
                }
            }
            else
            {
                CleanFormUser();
                Messages.Show(Page, Messages.USER_NOT_EXIST);
            }
        }

        protected void ChangeBlockedState(bool state)
        {
            lblBloqueadoUsuario.Visible = state;
            lblBloqueadoUsuario.Enabled = state;
            chboxBloqueadoUsuario.Visible = state;
            chboxBloqueadoUsuario.Enabled = state;
            BotonCancelarUsuario.Visible = state;
            BotonCancelarUsuario.Enabled = state;
        }

        protected void BtnEliminarUsuario_Click(object sender, EventArgs e)
        {
            DeleteUser();
        }

        private void DeleteUser()
        {
            if (new UserLogic().DeleteUserLogic(hidIdUsuario.Value, KEY))
            {
                CleanFormUser();
                LoadGridUser();
                Messages.Show(Page, Messages.DATA_ELIMINATED);
            }
            else
            {
                CleanFormUser();
                Messages.Show(Page, Messages.NO_DATA_ELIMINATED);
            }
        }



        protected void btnCrearVotacion_Click(object sender, EventArgs e)
        {
            Response.RedirectPermanent("Ingreso_Votacion.aspx");
        }
        protected void BtnEnviarMailUsuario_Click(object sender, EventArgs e)
        {
            string message = txtEditorEmailUsuario.Text;

            if (!string.IsNullOrWhiteSpace(message))
            {
                UserLogic userLogic = new UserLogic();
                Users user = userLogic.GetUserByIdLogic(hidEmailUsuario.Value, KEY);
                if (user != null)
                {
                    userLogic.SendEmailLogic(user, message, USER_MAIL, USER_PASSWORD, MAIL_SERVER);
                    CleanFormUser();
                    Messages.Show(Page, Messages.MESSAGE_SENT);
                }
                else
                {
                    CleanFormUser();
                    LoadGridUser();
                    Messages.Show(Page, Messages.USER_NOT_EXIST);
                }
            }
            else
            {
                CleanFormUser();
                LoadGridUser();
                Messages.Show(Page, Messages.NO_MESSAGE_SENT);
            }

        }

        protected void GridListaUsuario_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridListaUsuario.PageIndex = e.NewPageIndex;
            LoadGridUser();
        }

        protected void BotonCancelarUsuario_Click(object sender, EventArgs e)
        {
            CleanFormUser();
            BotonGuardarUsuario.Text = "Guardar";
            ChangeBlockedState(false);
        }

        protected void BtnActualizarUsuario_Click(object sender, ImageClickEventArgs e)
        {
            LoadGridUser();
        }
        #endregion

        protected void BtnLogout_Click(object sender, ImageClickEventArgs e)
        {
            Response.RedirectPermanent("~/Seguridad/Logout.aspx");
        }

        protected void Imagebtn_ReporteGeneral_Click(object sender, ImageClickEventArgs e)
        {
            Session["reporte"] = "general";
            Response.RedirectPermanent("Reportes.aspx");

        }

        protected void ImageButtonAdminUsuario_Click(object sender, ImageClickEventArgs e)
        {
            Response.RedirectPermanent("../Acceso_Usuario/Administracion_Votante.aspx");
        }
    }
}